import { h } from 'vue';

import { Modal } from 'ant-design-vue';
import CircularJSON from 'circular-json';

import {
  get1688ToDouyinProduct,
  get1688ToDouyinProductDetail,
  get1688ToDouyinProductList,
  getProductDetailById,
} from '#/api';
import { auto1688stor, indlyfor1688todystor, useAuthStore } from '#/store';
import { in1688ToDoudianStore } from '#/store/modules';

// 获取详情
export function get1688ProductDetail(itemId: number) {
  getProductDetailById({ offerIds: itemId }).then(() => {});
}
// 获取发布到抖店的详情
export function get1688ProductDetailToShop(itemId: number) {
  // const getInterId =

  const auto1688storTres = auto1688stor();
  const nowData = auto1688storTres.auto1688.nowSelectDyShop;
  if (!nowData) return;
  const upData = {
    offerId: itemId,
    shopId: nowData.shopId,
  };

  get1688ToDouyinProduct(upData).then(() => {
    // console.log('123465456', res);
  });
}

// 获取过滤完的商品详情
export function get1688ToDouyinProductDetailFuc(
  itemId: number[],
  shopId: number,
) {
  return new Promise((resolve, reject) => {
    const auto1688storTres = auto1688stor();
    const nowData = auto1688storTres.auto1688.nowSelectDyShop;
    if (!nowData) return;
    const upData = {
      offerIds: itemId,
      shopId: shopId || nowData.shopId,
    };
    get1688ToDouyinProductDetail(upData)
      .then((res) => {
        // console.log('详情', res);
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 发布前检查

export function checkBeforePublish(data: any) {
  const pubInfoErrs: any = {
    errNum: 0,
    errList: [],
  };
  data.forEach((item: any) => {
    item.productDetailList.forEach((_item2: any, index: number) => {
      pubInfoErrs.errNum += _item2.errAlls?.errNum || 0;
      if (!_item2.categoryId) {
        Modal.error({
          title: '发布前检查',
          content: h('div', ' 存在分类未选择商品，无法发布，请完成后发布'),
        });
        throw new Error('请选择分类');
      }
      if (_item2.errAlls?.errNum > 0) {
        pubInfoErrs.errList.push({
          shopName: item.shopName,
          index: index + 1,
          name: _item2.goodsTitle,
          errList: _item2.errAlls.errList,
        });
      }
    });
  });
  if (pubInfoErrs.errNum > 0) {
    Modal.confirm({
      title: '发布前检查',
      content: h('div', null, [
        h(
          'p',
          '发布的商品存在未完成的必填项，强行发布可能上货会失败，是否继续发布？',
        ),
        h('p', `错误数量：${pubInfoErrs.errNum}`),
      ]),
      onOk: () => {
        publishProduct(data);
      },

      okText: '坚持发布',
      cancelText: '返回修改',
    });
  } else {
    publishProduct(data);
  }
}
// 发布
export function publishProduct(data: any) {
  const in1688ToDoudian = in1688ToDoudianStore();

  in1688ToDoudian.lodingBool = true;
  const copyData = CircularJSON.parse(CircularJSON.stringify(data));
  const upDatas: any = [];
  copyData.forEach((item: any) => {
    item.productDetailList.forEach((_item2: any) => {
      // console.log('_item2', _item2);
      upDatas.push(formatPropertyData(_item2));
    });
  });
  // in1688ToDoudian.lodingBool = false;
  // console.log('upDatas', upDatas);
  // return;
  function moveSelectGoods() {
    in1688ToDoudian.shopTabs = in1688ToDoudian.shopTabs.filter((item: any) => {
      data.forEach((item2: any) => {
        if (item2.shopId === item.shopId) {
          item.productDetailList = item.productDetailList.filter(
            (item3: any) => {
              return !item2.productDetailList
                .map((item4: any) => item4.offerId)
                .includes(item3.offerId);
            },
          );
        }
      });
      if (
        item.productDetailList.length > 0 &&
        !item.productDetailList
          .map((item4: any) => item4.offerId)
          .includes(in1688ToDoudian.nowSelectGood)
      ) {
        in1688ToDoudian.nowSelectGood = item.productDetailList[0].offerId;
      }
      return item.productDetailList.length > 0;
    });
  }
  // console.log('upDatas', upDatas);
  // return;
  get1688ToDouyinProductList(upDatas)
    .then((_res) => {
      if (!_res) return;
      const getUpErrList = [];
      for (const key in _res) {
        getUpErrList.push(..._res[key].filter((item: any) => item.dyMsg));
        // _res[key].forEach((item: any) => {
        //   if (item.dyMsg) {
        //     item.dyMsg = item.dyMsg.replace(/<br>/g, '\n');
        //   }
        // })
      }

      if (getUpErrList.length > 0) {
        in1688ToDoudian.lodingBool = false;
        return Modal.error({
          title: '发布失败商品',
          content: h('div', null, [
            h('p', '以下商品发布失败，请检查后重新发布'),
            h(
              'div',
              getUpErrList.map((item: any) =>
                h('div', { innerHTML: item.dyMsg }),
              ),
            ),
          ]),
          onOk() {
            // in1688ToDoudian.lodingBool = false;
          },
        });
      }
      Modal.confirm({
        title: '提交成功',
        okText: '前往查看',
        content: h('div', {}, [
          h('p', '商品发布任务已成功提交， 发布结果请前往 <铺货记录> 查看'),
          // h('p', 'some messages...some messages...'),
        ]),
        onCancel() {
          moveSelectGoods();
          in1688ToDoudian.lodingBool = false;
        },
        onOk() {
          moveSelectGoods();
          const useAuth = useAuthStore();
          const pathname = location.pathname;
          if (pathname === '/in-doudian-get-1688') {
            const indlyfor1688tody = indlyfor1688todystor();
            let url =
              'https://dly1688.lntelliai.com/records/up-pruduct-records';
            if (indlyfor1688tody.shopData && indlyfor1688tody.shopData.shopId) {
              url = `${url}?shopData=${JSON.stringify(indlyfor1688tody.shopData)}`;
            }
            window.open(url, url);
          } else {
            useAuth.router.push({
              path: '/records/up-pruduct-records',
            });
          }
        },
      });
      in1688ToDoudian.lodingBool = false;
    })
    .finally(() => {
      in1688ToDoudian.lodingBool = false;
    });
}

function formatPropertyData(data: any) {
  const setDataInfo = {
    // 基础信息
    shopId: data.shopId,
    offerId: data.offerId,
    attributesList: data.attributesList,
    // 类目
    categoryId: data.categoryId,
    categoryId1688: data.categoryId1688,
    categoryIds: data.categoryIds,
    categoryId1688s: data.categoryId1688s,

    // 标题
    goodsTitle: data.goodsTitle,
    // 导购
    shortProductName: data.shortProductName,
    // 属性
    propertyList: setpropertyList(data.propertyList),

    // 商品主图
    mainPicList: data.mainPicList,

    // 3:4主图
    mainImageThreeToFourList: data.mainImageThreeToFourList, // [], // data.mainImageThreeToFourList

    // 视频
    materialvideoUrl: data.materialvideoUrl || '',

    // 测评短视频
    isEvaluateOpened: data.isEvaluateOpened ? '1' : '0',

    // 白底图
    whiteBackGroundPicUrl: data.whiteBackGroundPicUrl || '',

    // 详情图
    descPicList: data.descPicList,

    // 规格列表
    specInfo: (() => {
      data.specInfo.specValues = data.specInfo.specValues.map((item: any) => {
        item.propertyName = item.sellPropertyName;
     
        if (item.valueDisplayStyle === 'measure') {
          item.values.forEach((item2: any) => {

            const measureTemplates=item2.measureTemplates

            console.log("measureTemplates",measureTemplates)

            if(measureTemplates!=undefined){

              const getCOnter = measureTemplates.find(
                (tenpID: any) => item2.selectmeasureitem === tenpID.templateId,
              );
              item2.measureInfo = getCOnter;
              delete item2.measureTemplates;
            }
          });
        }
        return item;
      });

      return data.specInfo;
    })(),

    // sku列表
    specPricesV2: data.specPricesV2.map((item: any) => {
      item.price = Number((item.price * 100).toFixed(0));
      item.supplyPrice = Number((item.supplyPrice * 100).toFixed(0));
      item.sellProperties.forEach((item2: any, index: number) => {
        item2.propertyName = data.specInfo.specValues[index].sellPropertyName;
      });
      // console.log(' data.specInfo.specValues', data.specInfo.specValues);
      return item;
    }),

    // 其他配置
    commonShop: data.commonShop || null,

    // 资质
    qualityList:
      data.rule?.qualificationRule
        ?.map((item: any) => {
          let err = false;
          if (!item.fileList || item.fileList.length === 0) return null;
          const upDtata = {
            qualityKey: item.key,
            qualityName: item.name,
            qualityAttachments: (() => {
              return item.fileList.map((item2: any) => {
                return {
                  media_type: 1,
                  url: (() => {
                    if (!item2.response || item2.response.code !== 200) {
                      err = true;
                      return null;
                    }
                    return item2.response.data[0];
                  })(),
                };
              });
            })(),
          };
          return err ? null : upDtata;
        })
        ?.filter((itemw: any) => itemw !== null) || [],

    // 尺码模版
    templateId: data.templateId || null,

    minOrderQuantity: data.minOrderQuantity || null,
    limitPerBuyer: data.limitPerBuyer || null,
    wangwangAccount: data.wangwangAccount || null,
    supportChannels: data.supportChannels || null,
  };
  return setDataInfo;
}
function setpropertyList(list: any) {
  return list.map((item: any) => {
    // console.log('item', item);
    switch (item.type) {
      case 'measure': {
        // console.log(item);
        // item.measureTemplates?.forEach((item2: any) => {
        //   item2.valueModules?.forEach((item3: any) => {
        //     const uteiName = item3.units?.find(
        //       (item4: any) => item.optionsValue.unit === item4.unitId,
        //     )?.unitName;
        //     // console.log('uteiName', uteiName);
        //     // if (!item.optionsValue.value) {
        //     //   item.optionsValue = null;
        //     // }
        //     item.optionsValue = [
        //       { name: (item.optionsValue.value || '0') + uteiName },
        //     ];
        //   });
        // });
        item.optionsValue = item.measureTemplates;
        break;
      }
      case 'multi_select': {
        item.optionsValue =
          item.optionsValue?.map((item2: any) => {
            return item.options.find((item3: any) => item3.value === item2);
          }) || [];
        break;
      }
      case 'multi_value_measure': {
        // console.log('item', item);
        // console.log('item.optionsValue', item.optionsValue);
        item.optionsValue = item.optionsValue.map((item2: any) => {
          // console.log('valueId', valueId);
          const uite = item.measureTemplates[0].valueModules[1].units[0];
          // console.log('uite', uite);
          // console.log('huhuh', item2.valueId + item2.value + uite.unitName);
          const beforData = {
            name: item2.valueId + item2.value + uite.unitName,
            value: 0,
            diyType: 1,
            measureInfo: {
              values: [
                {
                  moduleId: item.measureTemplates[0].valueModules[0].moduleId,
                  value: item2.valueId,
                  unitId: 0,
                },
                {
                  moduleId: item.measureTemplates[0].valueModules[1].moduleId,
                  unitName: uite.unitName,
                  value: item2.valueId,
                  unitId: uite.unitId,
                },
              ],
              valueName: item2.valueId + item2.value + uite.unitName,
              templateId: item.measureTemplates[0].templateId,
            },
          };
          return beforData;
          
        });
        // console.log('datwr', datwr);
        // item.optionsValue = datwr;
        // item.optionsValue = item.optionsValue.map((item2: any) => {
        //   return {
        //     name: item2.valueId || '',
        //     value: item2.value || 0,
        //   };
        // });
        // console.log(' item.optionsValue', item.optionsValue);
        break;
      }
      case 'select': {
        item.optionsValue = (() => {
          const findData = item.options.find(
            (item2: any) => item2.value === item.optionsValue,
          );
          return findData ? [findData] : [];
        })();
        break;
      }
      case 'text': {
        item.optionsValue = [
          {
            name: item.optionsValue || '',
            value: 0,
          },
        ];
        break;
      }
      default: {
        break;
      }
    }

    return item;
  });
}
